package com.bing.mvc;

import com.bing.utils.MyCharacterEscapeHandler;
import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;

import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;
import java.io.IOException;
import java.io.Writer;

/**
 * Created by kaibb on 2014/11/30.
 */
public class MyJaxb2HttpMessageConverter extends Jaxb2RootElementHttpMessageConverter {

    private final static Logger logger = LoggerFactory.getLogger(MyJaxb2HttpMessageConverter.class);

    @Override
    protected void customizeMarshaller(Marshaller marshaller) {
        try {
            logger.info("setCustomizeMarshaller:{}", marshaller.getClass().getName());
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//去掉生成xml的默认报文头。
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
//转换所有的适配字符，包括xml实体字符&lt;和&gt;，xml实体字符在好多处理xml
//的框架中是处理不了的，除非序列化。
            marshaller.setProperty("com.sun.xml.bind.characterEscapeHandler",
                    new MyCharacterEscapeHandler());
        } catch (PropertyException e) {
            logger.error("customizeMarshaller error:", e);
        }
    }
}
